package com.work.demo.idempotent;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Slf4j
@Component
public class IdempotenceSupportAdvice {

    @Resource
    private Idempotence idempotence;
    @Resource
    IdempotenceUtil idempotenceUtil;

    @Pointcut("@annotation(com.work.demo.idempotent.IdempotenceRequired)")
    public void idempotenceMethod() {

    }

    @AfterThrowing(value = "idempotenceMethod()()", throwing = "e")
    public void afterThrowing(Throwable e) {
        if (!(e instanceof IdempotencyException)){
            String idempotenceId = idempotenceUtil.getHeaderIdempotenceId();
            idempotence.record(idempotenceId,1800);
        }
    }

    @Around(value = "idempotenceMethod()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String idempotenceId = idempotenceUtil.getHeaderIdempotenceId();
        if (StringUtils.isEmpty(idempotenceId)){
            return joinPoint.proceed();
        }

        boolean exist = idempotence.check(idempotenceId);
        if (!exist){
            throw new IdempotencyException("{success:false,请勿重复操作哦}");
        }

        idempotence.delete(idempotenceId);
        return joinPoint.proceed();
    }

}
